package ar.edu.itba.it.paw.domain;

import java.util.Date;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.OneToMany;

import ar.edu.itba.it.paw.domain.exceptions.InvalidOfferException;
import ar.edu.itba.it.paw.domain.exceptions.InvalidOperationException;

@Entity
public class Auction extends Product{
	
	
	@OneToMany(cascade=CascadeType.ALL, mappedBy = "auction")
	private List<Offer> offers;
	private boolean ended;
	
	protected Auction(){
		super();
	}
	
	public Auction(String name, String description, Date release_date ,Category category, float price, int quantity, boolean state, User owner){
		super(name,description,release_date,category,price,quantity,state,owner);
		offers = new ArrayList<Offer>();
	}
	
	public List<Offer> getOffers(){
		return offers;
	}
	
	public boolean hasOffers(){
		if(offers.size() == 0)
			return false;
		else
			return true;
	}
	
	public void addOffer(Offer offer) throws InvalidOfferException, InvalidOperationException{
		if(this.getOwner().equals(offer.getUser())){
			throw new InvalidOperationException();
		}
		if(offers.size() == 0){
			if(getBasePrice() >= offer.getOffer())
				throw new InvalidOfferException();
			else
				offers.add(offer);
		}else{
			if(offers.get(offers.size()-1).getOffer() >= offer.getOffer()){
				throw new InvalidOfferException();
			}
			else{
				offers.add(offer);
			}
		}
	}
	
	public Offer getOffer(Date offer_date){
		if(offer_date == null)
			throw new IllegalArgumentException("Illegal Date");
		else{
			for(int i=0; i<offers.size(); i++){
				if(offer_date.equals(offers.get(i).getOffer_date())){
					return offers.get(i);
				}
			}
			return null;
		}
	}

	public float getPrice(){
		float maxprice = getBasePrice();
		if(offers.size() != 0){
			maxprice = offers.get(0).getOffer();
			for(int i=1; i<offers.size(); i++){
				if(offers.get(i).getOffer() > maxprice){
					maxprice = offers.get(i).getOffer();
				}
			}
		}
		
		return maxprice;
	}
	
	public float getBasePrice(){
		return super.getPrice();
	}

	public void setEnded(boolean ended) {
		this.ended = ended;
	}

	public boolean isEnded() {
		return ended;
	}
	
	public User getUserBestOffer(){
		Offer best_offer = getOffers().get(0);
		for(Offer offer : getOffers()){
			if(offer.getOffer() > best_offer.getOffer()){
				best_offer = offer;
			}
		}
		return best_offer.getUser();
	}
	
}
